"""
邮件内容处理服务 - 处理动态表格和变量替换
"""
import json
import re
from typing import Dict, List, Any
from sqlalchemy.orm import Session
from services.data_source_service import DataSourceService
from services.system_variable_service import SystemVariableService


class EmailContentProcessor:
    """邮件内容处理器"""
    
    @staticmethod
    def process_email_content(db: Session, content: str, user_id: int) -> str:
        """
        处理邮件内容，解析动态表格标记和变量
        
        Args:
            db: 数据库会话
            content: 原始邮件内容
            user_id: 用户ID
            
        Returns:
            处理后的邮件内容
        """
        try:
            # 处理动态表格标记
            content = EmailContentProcessor._process_dynamic_tables(db, content, user_id)

            # 处理系统变量
            content = SystemVariableService.replace_system_variables(content)

            return content
            
        except Exception as e:
            print(f"处理邮件内容失败: {str(e)}")
            return content
    
    @staticmethod
    def _process_dynamic_tables(db: Session, content: str, user_id: int) -> str:
        """处理动态表格标记"""
        # 查找所有动态表格标记 - 使用更精确的匹配
        pattern = r'\{\{DYNAMIC_TABLE:(\{.*?\})\}\}'

        def replace_dynamic_table(match):
            try:
                json_str = match.group(1)
                print(f"解析动态表格JSON: {json_str}")

                # 解析JSON配置
                config = json.loads(json_str)
                print(f"解析后的配置: {config}")

                # 生成表格HTML
                table_html = EmailContentProcessor._generate_dynamic_table_html(
                    db, config, user_id
                )

                print(f"生成的表格HTML长度: {len(table_html)}")
                return table_html

            except json.JSONDecodeError as e:
                print(f"JSON解析失败: {str(e)}")
                print(f"原始JSON字符串: {json_str}")
                return f"<p>动态表格JSON解析失败: {str(e)}</p>"
            except Exception as e:
                print(f"处理动态表格标记失败: {str(e)}")
                return f"<p>动态表格处理失败: {str(e)}</p>"

        # 使用re.sub进行替换
        processed_content = re.sub(pattern, replace_dynamic_table, content)

        if processed_content != content:
            print("动态表格标记已处理")
        else:
            print("未找到动态表格标记")

        return processed_content
    
    @staticmethod
    def _generate_dynamic_table_html(db: Session, config: Dict[str, Any], user_id: int) -> str:
        """生成动态表格HTML"""
        try:
            data_source_id = config.get('dataSource')
            table_name = config.get('table')
            fields = config.get('fields', [])
            conditions = config.get('conditions', [])
            
            if not data_source_id or not table_name or not fields:
                return "<p>动态表格配置错误</p>"
            
            # 获取表数据
            conditions_json = json.dumps(conditions) if conditions else ""
            table_data = DataSourceService.get_table_data(
                db, data_source_id, table_name, 
                ','.join(fields), 100, conditions_json, user_id
            )
            
            if not table_data:
                return "<p>没有找到匹配的数据</p>"
            
            # 生成HTML表格
            html = '<table border="1" style="border-collapse: collapse; width: 100%; margin: 10px 0;">\n'
            
            # 表头
            html += '  <thead>\n    <tr style="background-color: #f5f5f5;">\n'
            for field in fields:
                html += f'      <th style="padding: 8px; border: 1px solid #ddd; text-align: left;">{field}</th>\n'
            html += '    </tr>\n  </thead>\n'
            
            # 表体
            html += '  <tbody>\n'
            for row in table_data:
                html += '    <tr>\n'
                for field in fields:
                    value = row.get(field, '')
                    # 处理None值和特殊字符
                    if value is None:
                        value = ''
                    else:
                        value = str(value).replace('<', '&lt;').replace('>', '&gt;')
                    html += f'      <td style="padding: 8px; border: 1px solid #ddd;">{value}</td>\n'
                html += '    </tr>\n'
            html += '  </tbody>\n</table>'
            
            return html
            
        except Exception as e:
            print(f"生成动态表格HTML失败: {str(e)}")
            return f"<p>动态表格生成失败: {str(e)}</p>"
    
    @staticmethod
    def _process_variables(content: str, variables: Dict[str, Any]) -> str:
        """处理普通变量替换"""
        for var_name, var_value in variables.items():
            pattern = f"{{{{{var_name}}}}}"
            content = content.replace(pattern, str(var_value))
        
        return content
